package zk_01.zookeeper;

import java.io.IOException;

import org.apache.log4j.chainsaw.Main;
import org.apache.zookeeper.AsyncCallback.StringCallback;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class MonitorMaster implements Watcher{
	private ZooKeeper zk;
	private String hostPort;
	
	private StringCallback getDataCallback = new StringCallback(){

		public void processResult(int rc, String path, Object ctx, String name) {
			switch(Code.get(rc)){
			case CONNECTIONLOSS:
				getData(path);
				break;
			case OK:
				System.out.println("get "+path+" successed");
				break;
			default:
				System.out.println("get "+path+" unSuccessed");
			}
		}
		
	};
	
	public void getData(String path){
		Stat stat = new Stat();
		try {
			String rlt = new String(zk.getData(path, true, stat));
			System.out.println("rlt:"+rlt);
		} catch (KeeperException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(stat);
	}
	
	public MonitorMaster(){}
	
	public MonitorMaster(String hostPort){
		this.hostPort=hostPort;
	}
	
	public void startZK() throws IOException{
		zk = new ZooKeeper(hostPort,15000,this);
	}
	
	public void stopZK() throws InterruptedException{
		zk.close();
	}

	public void process(WatchedEvent event) {
		System.out.println(event);
	}
	
	public static void main(String[] args) {
		MonitorMaster mm = new MonitorMaster("192.168.1.113:2181");
		try {
			mm.startZK();
			mm.getData("/master");
			Thread.sleep(100000);
			mm.stopZK();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
